﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EvincePayroll.Data;
using EvincePayroll.Utility;

namespace EvincePayroll.Logic
{

    public class LeaveRequstLogic : BaseLogic
    {
        public LeaveRequstLogic(string emailId)
            : base(emailId)
        { }


        public List<EmployeeLeaveRequestData> LeaveRequestsAdmin()
        {
            List<EmployeeLeaveRequestData> employeeLeaveRequestData = null;
            try
            {
                var statusId = db.GetAppOptionDataList().Where(x => x.ParamValue.Equals(Constants.LEAVE_REQUEST_PENDING)).Select(x => x.ParamId).FirstOrDefault().ToString();
                var employeeLeaveRequestList = db.GetEmployeeLeaveRequestDataList();
                var employeesList = db.GetEmployeeDataList();
                var appOptionList = db.GetAppOptionDataList();
                employeeLeaveRequestData = (from list in employeeLeaveRequestList
                                            join employee in employeesList on list.EmployeeId equals employee.ID
                                            join employeeReportTo in employeesList on list.ReportTo equals employeeReportTo.ID
                                            join employeeAssignTo in employeesList on list.AssignTo equals employeeAssignTo.ID
                                            join appOption in appOptionList on list.Status equals appOption.ParamId
                                            select new EmployeeLeaveRequestData
                                            {
                                                LeaveId = list.LeaveId,
                                                EmployeeId = list.EmployeeId,
                                                EmployeeStringId = employee.EmployeeId,
                                                TotalLeave = list.TotalLeave,
                                                LeaveReason = list.LeaveReason,
                                                FromDate = list.FromDate,
                                                ToDate = list.ToDate,
                                                Status = list.Status,
                                                CreatedDate = list.CreatedDate,
                                                ReportTo = list.ReportTo,
                                                AssignTo = list.AssignTo,
                                                ReportingManagerName = employeeReportTo.FirstName + " " + employeeReportTo.LastName,
                                                EmployeeFullName = employee.FirstName + " " + employee.LastName,
                                                AssigneToEmployee = employeeAssignTo.FirstName + " " + employeeAssignTo.LastName,
                                                LeaveType = list.LeaveType,
                                                LeaveStatus = appOption.ParamValue

                                            }).OrderBy(d => d.CreatedDate).ToList<EmployeeLeaveRequestData>();

                return employeeLeaveRequestData;
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        }
        public List<EmployeeLeaveRequestData> LeaveRequestsEmployee(EmployeeLeaveRequestData employeeLeaveReuestData, string emailId)
        {
            List<EmployeeLeaveRequestData> employeeLeaveRequestDataList = null;
            try
            {
                var employeeId = db.GetEmployeeDataList().Where(x => x.Email.Equals(emailId)).Select(x => x.ID).FirstOrDefault();
                var statusId = db.GetAppOptionDataList().Where(x => x.ParamValue.Equals(Constants.LEAVE_REQUEST_PENDING)).Select(x => x.ParamId).FirstOrDefault();
                var leaveType = db.GetAppOptionDataList().Where(x => x.ParamKey.Equals(Constants.LeaveType)).Select(x => x.ParamValue).ToList();
                if (employeeLeaveReuestData != null)
                {
                    employeeLeaveReuestData.EmployeeId = employeeId;
                    employeeLeaveReuestData.Status = statusId;
                    employeeLeaveReuestData.LeaveTypes = leaveType;
                    employeeLeaveReuestData.IsActive = false;
                    db.CreateEmployeeLeaveRequest(employeeLeaveReuestData);

                }
                employeeLeaveRequestDataList = db.GetEmployeeLeaveRequestDataList();

            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;

            }
            return employeeLeaveRequestDataList;

        }

        public List<EmployeeData> GetLeaveRequestsEmployeeData(string emailId, string userRoleName)
        {
            List<EmployeeData> employeeData = null;

            try
            {
                var employeeList = db.GetEmployeeDataList();
                var userRoleList = db.GetUserRoleDataList();//.Where(x => x.UserRoleId.Equals(userRole)).FirstOrDefault();
                var userRole = userRoleList.Where(x => x.UserRole.Equals(userRoleName)).FirstOrDefault();
                if (userRole != null)
                {
                    employeeData = (from employee in employeeList
                                    where employee.UserRoleId == userRole.UserRoleId //employee.UserRoleId.Equals(roleId)
                                    select new EmployeeData
                                    {
                                        ID = employee.ID,
                                        FirstName = employee.FirstName,
                                        LastName = employee.LastName,
                                        TemporaryAddress = employee.TemporaryAddress,
                                        City = employee.City,
                                        ContactNumber1 = employee.ContactNumber1,
                                        ContactNumber2 = employee.ContactNumber2,
                                        MiddleName = employee.MiddleName,
                                        Email = employee.Email,
                                        AlternateEmail = employee.Email,
                                        DateOfBirth = employee.DateOfBirth,
                                        Gender = employee.Gender,
                                        Image1 = employee.Image1,
                                        PermanentAddress = employee.PermanentAddress,
                                        Pincode = employee.Pincode,
                                        State = employee.State,
                                        Password = employee.Password,
                                        UserRoleId = (Guid)employee.UserRoleId,
                                        EmployeeId = employee.EmployeeId,
                                        ReportToManager = employee.FirstName + " " + employee.LastName,
                                        AssignToEmployee = employee.FirstName + " " + employee.LastName

                                    }).ToList<EmployeeData>();
                }
                return employeeData;


            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;

            }

        }

        public bool UpdateLeaveRequestStatus(string leaveRequestId, string status, string message, string numberOfDays, DateTime fromDate, string flag)
        {
            bool result = false;
            try
            {
                EmployeeLeaveRequestData employeeLeaveRequestData = db.GetEmployeeLeaveRequestDataByLeaveId(leaveRequestId);
                var employeeList = db.GetEmployeeDataList();
                var leaveRequestData = db.GetEmployeeLeaveRequestDataByLeaveId(leaveRequestId);
                var employeeData = (from info in employeeList
                                    where info.ID == leaveRequestData.EmployeeId
                                    select info).FirstOrDefault();
                if (status.Trim().Equals(Constants.LEAVE_REQUEST_APPROVED))
                {
                    MailSend(employeeData.Email, leaveRequestId, status);
                }
                if (status.Trim().Equals(Constants.LEAVE_REQUEST_NOT_APPROVED))
                {
                    MailSend(employeeData.Email, leaveRequestId, status);
                }
                var attendanceList = db.GetAttendanceDataList();
                var leaveRequestList = db.GetEmployeeLeaveRequestDataList();
                Guid leaveStatusId = db.GetAppOptionDataList().Where(x => x.ParamValue.Equals(Constants.ATTENDANCE_LEAVE)).Select(x => x.ParamId).FirstOrDefault();
                Guid statusId = db.GetAppOptionDataList().Where(x => x.ParamValue.Equals(status.Trim())).Select(x => x.ParamId).FirstOrDefault();
                var leaveRequest = (from leaves in leaveRequestList
                                    where leaves.LeaveId.ToString() == leaveRequestId
                                    select leaves).FirstOrDefault();
                if (leaveRequest != null && statusId != null)
                {
                    leaveRequest.CreatedDate = System.DateTime.Now;
                    leaveRequest.Status = (Guid)statusId;
                    leaveRequest.Remark = message;
                    leaveRequest.IsActive = true;
                    db.UpdateEmployeeLeaveRequest(leaveRequest);
                    if (fromDate != null && numberOfDays != null && flag != "1")
                    {
                        //int fromDay = 0; int fromMonth = 0; int fromYear = 0;
                        //fromDay = Convert.ToInt16(fromDate.Split('/')[0]);
                        //fromMonth = Convert.ToInt16(fromDate.Split('/')[1]);
                        //fromYear = Convert.ToInt16(fromDate.Split('/')[2]);
                        for (int i = 0; i < Convert.ToInt16(numberOfDays); i++)
                        {
                            var date = fromDate;
                            date = date.AddDays(i);
                            var checkExistingLeaves = attendanceList.Where(x => x.Date.Equals(date) && x.EmployeeId.Equals(employeeData.ID)).Select(x => x.AttendanceId).FirstOrDefault();
                            if (checkExistingLeaves == Guid.Empty)
                            {
                                AttendanceData attendance = new AttendanceData();
                                attendance.AttendanceId = Guid.NewGuid();
                                attendance.EmployeeId = leaveRequest.EmployeeId;
                                attendance.ArrivingTime = DateTime.MaxValue;
                                attendance.LeavingTime = DateTime.MaxValue;
                                attendance.Date = date;
                                //Status = leaveStatusId
                                attendance.Status = statusId;
                                db.CreateAttendance(attendance);
                            }
                        }
                        employeeLeaveRequestData = db.GetEmployeeLeaveRequestDataByLeaveId(leaveRequestId);
                        if (employeeLeaveRequestData.IsActive == true)
                        {
                            //--
                            result = CalculateLeaveOfEmployee(employeeLeaveRequestData, false);
                        }

                    }
                    else if (fromDate != null && numberOfDays != null && flag == "1")
                    {
                        //var attendance = null;
                        //int fromDay = 0; int fromMonth = 0; int fromYear = 0;
                        //fromDay = Convert.ToInt16(fromDate.Split('/')[0]);
                        //fromMonth = Convert.ToInt16(fromDate.Split('/')[1]);
                        //fromYear = Convert.ToInt16(fromDate.Split('/')[2]);
                        for (int i = 0; i < Convert.ToInt16(numberOfDays); i++)
                        {
                            var date = fromDate;
                            date = date.AddDays(i);
                            Guid checkExistingLeaves = attendanceList.Where(x => x.Date.Equals(date)).Select(x => x.AttendanceId).FirstOrDefault();
                            if (checkExistingLeaves != Guid.Empty)
                            {
                                AttendanceData attendance = new AttendanceData();
                                attendance = (from value in attendanceList
                                              where value.AttendanceId == checkExistingLeaves
                                              select value).FirstOrDefault();
                                if (attendance != null)
                                    db.DeleteAttendance(attendance.AttendanceId.ToString());
                            }

                        }
                        if (employeeLeaveRequestData.IsActive == true)
                        {
                            //++
                            result = CalculateLeaveOfEmployee(employeeLeaveRequestData, true);
                        }
                        //db.Attendances.DeleteAllOnSubmit(attendanceList);
                    }





                    result = true;
                }
                return result;

            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        }
        public List<EmployeeLeaveRequestData> GetRequestEmployee(string emailId, string status)
        {
            try
            {
                List<EmployeeLeaveRequestData> employeeLeaveRequestData;
                var leaveRequestList = db.GetEmployeeLeaveRequestDataList();
                var appOptionList = db.GetAppOptionDataList();
                var employeeId = db.GetEmployeeDataList().Where(e => e.Email.Equals(emailId)).Select(e => e.ID).FirstOrDefault();
                employeeLeaveRequestData = (from list in leaveRequestList
                                            join appOption in appOptionList on list.Status equals appOption.ParamId
                                            where list.EmployeeId.Equals(employeeId)
                                            select new EmployeeLeaveRequestData
                                            {
                                                LeaveId = list.LeaveId,
                                                LeaveReason = list.LeaveReason,
                                                FromDate = list.FromDate,
                                                ToDate = list.ToDate,
                                                LeaveType = list.LeaveType,
                                                LeaveStatus = appOption.ParamValue,
                                                CreatedDate = list.CreatedDate,
                                                Remark = list.Remark
                                            }).ToList<EmployeeLeaveRequestData>();
                return employeeLeaveRequestData;

            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        }
        public bool AddData(EmployeeLeaveRequestData employeeLeaveRequest, string emailId)
        {
            bool result = false;
            try
            {

                if (employeeLeaveRequest != null)
                {
                    var statusId = db.GetAppOptionDataList().Where(x => x.ParamId.Equals(employeeLeaveRequest.Status)).Select(x => x.ParamId).FirstOrDefault();
                    employeeLeaveRequest.Status = statusId;
                    result = db.CreateEmployeeLeaveRequest(employeeLeaveRequest);

                }
                result = true;
                if (result == true)
                {
                    employeeLeaveRequest.LeaveId = db.GetEmployeeLeaveRequestDataList().Where(x => x.EmployeeId.Equals(employeeLeaveRequest.EmployeeId) && x.LeaveReason.Equals(employeeLeaveRequest.LeaveReason)).Select(x => x.LeaveId).FirstOrDefault();
                    Guid statusIdAttendance = db.GetAppOptionDataList().Where(x => x.ParamId.Equals(employeeLeaveRequest.Status)).Select(x => x.ParamId).FirstOrDefault();
                    if (employeeLeaveRequest != null && statusIdAttendance != null)
                    {
                        employeeLeaveRequest.CreatedDate = System.DateTime.Now;
                        employeeLeaveRequest.Status = (Guid)statusIdAttendance;
                        employeeLeaveRequest.Remark = employeeLeaveRequest.Remark;
                        db.UpdateEmployeeLeaveRequest(employeeLeaveRequest);
                        if (employeeLeaveRequest.FromDate != null && employeeLeaveRequest.TotalLeave != null)
                        {
                            int value = 0;

                            value = Convert.ToInt16(employeeLeaveRequest.TotalLeave);


                            //int fromDay = 0; int fromMonth = 0; int fromYear = 0;
                            //fromDay = Convert.ToInt16(employeeLeaveRequest.FromDate.Split('/')[0]);
                            //fromMonth = Convert.ToInt16(employeeLeaveRequest.FromDate.Split('/')[1]);
                            //fromYear = Convert.ToInt16(employeeLeaveRequest.FromDate.Split('/')[2]);
                            for (int i = 0; i < value; i++)
                            {
                                var date = employeeLeaveRequest.FromDate;
                                date = date.AddDays(i);
                                var checkExistingLeaves = db.GetAttendanceDataList().Where(x => x.Date.Equals(employeeLeaveRequest.FromDate) && x.EmployeeId.Equals(employeeLeaveRequest.EmployeeId)).Select(x => x.AttendanceId).FirstOrDefault();
                                if (checkExistingLeaves == Guid.Empty)
                                {
                                    AttendanceData attendance = new AttendanceData();

                                    attendance.EmployeeId = employeeLeaveRequest.EmployeeId;
                                    attendance.ArrivingTime = DateTime.MaxValue;
                                    attendance.LeavingTime = DateTime.MaxValue;
                                    attendance.Date = date;
                                    attendance.Status = statusIdAttendance;
                                    db.CreateAttendance(attendance);
                                }
                            }
                            //db.Attendances.InsertAllOnSubmit(attendanceList);
                        }


                    }


                }

            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return result;
        }

        public bool UpdateData(EmployeeLeaveRequestData employeeLeaveRequest, Guid Id, string emailId)
        {
            bool result = false;
            try
            {
                if (employeeLeaveRequest != null)
                {
                    var leaveRequest = db.GetEmployeeLeaveRequestDataList().Where(x => x.LeaveId.Equals(Id)).FirstOrDefault();

                    leaveRequest.EmployeeId = employeeLeaveRequest.EmployeeId;
                    leaveRequest.TotalLeave = employeeLeaveRequest.TotalLeave;
                    leaveRequest.LeaveReason = employeeLeaveRequest.LeaveReason;
                    leaveRequest.FromDate = employeeLeaveRequest.FromDate;
                    leaveRequest.ToDate = employeeLeaveRequest.ToDate;
                    leaveRequest.LeaveType = employeeLeaveRequest.LeaveType;
                    leaveRequest.Status = employeeLeaveRequest.Status;
                    leaveRequest.CreatedDate = employeeLeaveRequest.CreatedDate;
                    leaveRequest.ReportTo = employeeLeaveRequest.ReportTo;
                    leaveRequest.AssignTo = employeeLeaveRequest.AssignTo;
                    leaveRequest.Remark = employeeLeaveRequest.Remark;

                    db.UpdateEmployeeLeaveRequest(leaveRequest);
                }
                result = true;
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return result;
        }

        public List<AppOptionData> getStatus(string emailId)
        {
            List<AppOptionData> appOptionData = null;
            try
            {
                var appOptionList = db.GetAppOptionDataList();
                appOptionData = (from list in appOptionList
                                 where list.ParamKey.Equals(Constants.ATTENDANCE)
                                 select new AppOptionData
                                 {
                                     ParamId = list.ParamId,
                                     ParamValue = list.ParamValue
                                 }).ToList<AppOptionData>();
                return appOptionData;
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        }
        public string DeleteData(int id, string emailId)
        {
            try
            {

                var employeeLeaveRequestList = db.GetEmployeeLeaveRequestDataList();
                var attendanceList = db.GetAttendanceDataList();
                var employeeLeaveRequest = employeeLeaveRequestList.Where(x => x.EmployeeId.Equals(id)).FirstOrDefault();
                var attendance = attendanceList.Where(x => x.EmployeeId.Equals(id)).FirstOrDefault();
                if (employeeLeaveRequest == null)
                    return "Record Not Found";
                db.DeleteEmployeeLeaveRequest(employeeLeaveRequest.LeaveId.ToString());
                db.DeleteAttendance(attendance.AttendanceId.ToString());

                return "ok";

            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        }

        public bool MarkAubsent()
        {
            try
            {
                DateTime date = DateTime.Now;
                var employeeList = db.GetEmployeeDataList().Select(x => x.ID).ToList();
                var attendanceList = db.GetAttendanceDataList().Where(x => x.Date.Equals(DateTime.Today)).ToList();
                var employeeLeaveRequestList = db.GetEmployeeLeaveRequestDataList();
                foreach (var info in employeeList)
                {
                    var empId = attendanceList.Where(x => x.EmployeeId.Equals(info)).Select(x => x.EmployeeId).FirstOrDefault();
                    if (empId == Guid.Empty)
                    {
                        var leaveStatus = employeeLeaveRequestList.Where(x => x.EmployeeId.Equals(info) && x.CreatedDate.Equals(DateTime.Today)).Select(x => x.Status).FirstOrDefault();
                        if (leaveStatus == db.GetAppOptionDataList().Where(x => x.ParamValue.Equals(Constants.LEAVE_REQUEST_NOT_APPROVED)).Select(x => x.ParamId).FirstOrDefault())
                        {
                            AttendanceData attendance = new AttendanceData();
                            attendance.EmployeeId = info;
                            attendance.ArrivingTime = DateTime.MaxValue;
                            attendance.LeavingTime = DateTime.MaxValue;
                            attendance.Date = DateTime.Today;
                            attendance.Status = db.GetAppOptionDataList().Where(x => x.ParamValue.Equals(Constants.ATTENDANCE_UN_APPROVED)).Select(x => x.ParamId).FirstOrDefault();
                            db.CreateAttendance(attendance);

                        }
                        else
                        {
                            AttendanceData attendance = new AttendanceData();
                            attendance.EmployeeId = info;
                            attendance.ArrivingTime = DateTime.MaxValue;
                            attendance.LeavingTime = DateTime.MaxValue;
                            attendance.Date = DateTime.Today;
                            attendance.Status = db.GetAppOptionDataList().Where(x => x.ParamValue.Equals(Constants.ATTENDANCE_ABSENT)).Select(x => x.ParamId).FirstOrDefault();
                            db.CreateAttendance(attendance);
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        }
        public bool CheckOut(string emailId, string reason)
        {
            bool result = false;
            try
            {
                var appOptionList = db.GetAppOptionDataList();
                var attendanceList = db.GetAttendanceDataList();

                var employeeList = db.GetEmployeeDataList();
                DateTime date = DateTime.Now;
                //  string newdate = "d/MM/yyyy";
                // string todayDate = date.ToString(newdate);
                // Int16 isActive = 1;
                Guid employeeId = employeeList.Where(x => x.Email.Equals(emailId.Trim())).Select(x => x.ID).FirstOrDefault();
                var attendanceLog = (from info in db.GetAttendanceLogDataList()
                                     where info.Date == DateTime.Today && info.EmployeeId == employeeId && info.IsActive == true
                                     select info).FirstOrDefault();
                // var attendanceLog = db.GetAttendanceLogDataList().Where(x => x.Date.Equals(todayDate.Trim()) && x.EmployeeId.Equals(employeeId) && x.LeavingTime.Equals(null)).ToList();
                DateTime startTime = attendanceLog.ArrivingTime;
                DateTime leavingTime = System.DateTime.Now;
                DateTime endTime = leavingTime;
                TimeSpan ts = endTime - startTime;
                var presentToday = (from info in attendanceList
                                    where info.Date.Equals(DateTime.Today) && info.EmployeeId.Equals(employeeId)
                                    select info).FirstOrDefault();
                if (attendanceLog != null)
                {
                    attendanceLog.TotalHours = ts.Hours.ToString("00") + ":" + ts.Minutes.ToString("00") + ":" + ts.Seconds.ToString("00");
                    attendanceLog.LeavingTime = leavingTime;
                    attendanceLog.Remark = reason;
                    attendanceLog.IsActive = false;
                    db.UpdateAttendanceLog(attendanceLog);
                }
                if (presentToday != null)
                {


                    presentToday.LeavingTime = System.DateTime.Now;
                    db.UpdateAttendance(presentToday);
                    result = true;
                }
                //db.CheckOut(emailId,reason);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return result;
        }
        public bool CheckIn(string emailId)
        {
            bool result = false;
            try
            {
                var appOptionList = db.GetAppOptionDataList();
                var attendanceList = db.GetAttendanceDataList();
                var employeeList = db.GetEmployeeDataList();
                var employeeData = (from data in employeeList
                                    where data.Email == emailId
                                    select data).FirstOrDefault();
                if (employeeData != null)
                {


                    AttendanceData attendance = new AttendanceData();
                    AttendanceLogData attendanceLog = new AttendanceLogData();
                    // DateTime date = DateTime.Now;
                    //string newdate = "d/MM/yyyy";
                    //string todayDate = date.ToString(newdate);
                    Guid presentStatusId = appOptionList.Where(x => x.ParamValue.Equals(Constants.ATTENDANCE_PRESENT)).Select(x => x.ParamId).FirstOrDefault();
                    var presentToday = (from info in attendanceList
                                        where info.Date.Equals(DateTime.Today) && info.EmployeeId.Equals(employeeData.ID)
                                        select info).FirstOrDefault();
                    if (presentToday != null)
                    {

                        attendanceLog.AttendanceId = presentToday.AttendanceId;
                        attendanceLog.EmployeeId = presentToday.EmployeeId;
                        attendanceLog.TotalHours = string.Format("{0}:{1}:{2}", 00, 00, 00);
                        attendanceLog.ArrivingTime = DateTime.Now;
                        attendanceLog.LeavingTime = DateTime.MaxValue;
                        attendanceLog.Date = DateTime.Today;
                        attendanceLog.Remark = string.Empty;
                        attendanceLog.IsActive = true;
                        db.CreateAttendanceLog(attendanceLog);

                    }
                    if (presentToday == null)
                    {

                        attendance.EmployeeId = employeeData.ID;
                        attendance.ArrivingTime = DateTime.Now;
                        attendance.LeavingTime = DateTime.MaxValue;
                        attendance.Date = DateTime.Today;
                        attendance.Status = presentStatusId;
                        db.CreateAttendance(attendance);

                        var attendanceTodayId = db.GetAttendanceDataList().Where(x => x.EmployeeId.Equals(employeeData.ID) && x.Date.Equals(DateTime.Today)).Select(x => x.AttendanceId).FirstOrDefault();


                        attendanceLog.AttendanceId = attendanceTodayId;
                        attendanceLog.EmployeeId = employeeData.ID;
                        attendanceLog.TotalHours = string.Format("{0}:{1}:{2}", 00, 00, 00);
                        attendanceLog.ArrivingTime = DateTime.Now;
                        attendanceLog.LeavingTime = DateTime.MaxValue;
                        attendanceLog.Remark = string.Empty;
                        attendanceLog.IsActive = true;
                        attendanceLog.Date = DateTime.Today;
                        db.CreateAttendanceLog(attendanceLog);
                        //       return db.CheckIn(emailId);
                        result = true;

                    }
                }
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return result;
        }

        public void MailSend(string emailId, string leaveRequestId, string status)
        {
            var employeesList = db.GetEmployeeDataList();
            var employeeLeaveRequestLeaveList = db.GetEmployeeLeaveRequestDataList();
            var employeeData = (from info in employeesList
                                where info.Email == emailId
                                select info).FirstOrDefault();
            var leaveData = (from leave in employeeLeaveRequestLeaveList
                             where leave.LeaveId.ToString() == leaveRequestId
                             select leave).FirstOrDefault();
            var toAddress = emailId;
            string subject = "Leave Request Status";
            string body = "From: Admin \n";
            if (status.Trim().Equals(Constants.LEAVE_REQUEST_APPROVED))
            {
                body += "Dear " + employeeData.FirstName + ", Your leave is Approved \n From Date: " + leaveData.FromDate + " - To Date: " + leaveData.ToDate + " \n Regards\n Admin.";
            }
            else if (status.Trim().Equals(Constants.LEAVE_REQUEST_NOT_APPROVED))
            {
                body += "Dear " + employeeData.FirstName + ", Your leave is Not Approved \n From Date: " + leaveData.FromDate + " - To Date: " + leaveData.ToDate + " \n Regards\n Admin.";
            }
            MailSending mail = new MailSending();
            mail.SendMail(toAddress, subject, body);

        }

        public LeaveMasterData GetLeaveMasterData(string emailId, string roleId)
        {
            LeaveMasterData leaveMaster = null;
            try
            {
                if (!string.IsNullOrEmpty(roleId))
                    leaveMaster = db.GetLeaveMasterDataList().Where(x => x.RoleId.ToString().Equals(roleId)).FirstOrDefault();
                else
                    leaveMaster = db.GetLeaveMasterDataList().Where(x => x.Year.Year.Equals(DateTime.Now.Year)).FirstOrDefault();
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return leaveMaster;
        }

        public EmployeeLeaveMasterData GetEmoloyeeLeaveMasterData(EmployeeData employee)
        {
            EmployeeLeaveMasterData empLeaveMaster = null;
            try
            {
                empLeaveMaster = db.GetEmployeeLeaveMasterDataList().Where(x => x.EmployeeId.Equals(employee.ID)).FirstOrDefault();
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return empLeaveMaster;
        }

        public LeaveMasterData CreateLeaveMaster(LeaveMasterData leaveMaster, string emailId)
        {
            LeaveMasterData leaveMasterData = null;
            try
            {
                if (leaveMaster.LeaveMasterId == Guid.Empty)
                    db.CreateLeave(leaveMaster);
                else
                    db.UpdateLeaveMaster(leaveMaster);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return leaveMasterData;
        }

        public bool CalculateLeaveOfEmployee(EmployeeLeaveRequestData employeeLeaveRequestData, bool flag)
        {
            bool result = false;
            EmployeeLeaveMasterData leaveMasterData = null;
            var leaveName = db.GetAppOptionDataList().Where(x => x.ParamId.ToString().Equals(employeeLeaveRequestData.LeaveStatusType)).Select(x => x.ParamValue).FirstOrDefault();
            leaveMasterData = db.GetEmployeeLeaveMasterDataList().Where(x => x.EmployeeId.Equals(employeeLeaveRequestData.EmployeeId)).FirstOrDefault();
            try
            {
                if (employeeLeaveRequestData.LeaveStatusType != null)
                {
                    // string count = 1;
                    if (flag == false)
                    {
                        if (leaveName == "SickLeave")
                        {

                            leaveMasterData.Sickleave = leaveMasterData.Sickleave - Convert.ToDecimal(employeeLeaveRequestData.TotalLeave);



                        }
                        else if (leaveName == "PrivilageLeave")
                        {
                            leaveMasterData.PrivilageLeave = leaveMasterData.PrivilageLeave - Convert.ToDecimal(employeeLeaveRequestData.TotalLeave);
                        }
                        else if (leaveName == "CasualLeave")
                        {
                            leaveMasterData.CasualLeave = leaveMasterData.CasualLeave - Convert.ToDecimal(employeeLeaveRequestData.TotalLeave);
                        }
                        else if (leaveName == "LeaveWithoutPay")
                        {
                            leaveMasterData.LeaveWithoutPay = leaveMasterData.LeaveWithoutPay - Convert.ToDecimal(employeeLeaveRequestData.TotalLeave);
                        }


                        result = db.UpdateEmployeeLeaveMaster(leaveMasterData);
                    }
                    else
                    {

                        if (leaveName == "SickLeave")
                        {

                            leaveMasterData.Sickleave = leaveMasterData.Sickleave + Convert.ToDecimal(employeeLeaveRequestData.TotalLeave);



                        }
                        else if (leaveName == "PrivilageLeave")
                        {
                            leaveMasterData.PrivilageLeave = leaveMasterData.PrivilageLeave + Convert.ToDecimal(employeeLeaveRequestData.TotalLeave);
                        }
                        else if (leaveName == "CasualLeave")
                        {
                            leaveMasterData.CasualLeave = leaveMasterData.CasualLeave + Convert.ToDecimal(employeeLeaveRequestData.TotalLeave);
                        }
                        else if (leaveName == "LeaveWithoutPay")
                        {
                            leaveMasterData.LeaveWithoutPay = leaveMasterData.LeaveWithoutPay + Convert.ToDecimal(employeeLeaveRequestData.TotalLeave);
                        }


                        result = db.UpdateEmployeeLeaveMaster(leaveMasterData);




                    }
                }
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }

            return result;



        }

        public bool CheckLeave(string leaveType, string email)
        {
            bool result = false;
            EmployeeLeaveMasterData leaveMasterData = null;
            var employeeId = db.GetEmployeeDataList().Where(x => x.Email.Equals(email)).Select(x => x.EmployeeId).FirstOrDefault();
            var leaveName = db.GetAppOptionDataList().Where(x => x.ParamId.ToString().Equals(leaveType)).Select(x => x.ParamValue).FirstOrDefault();
            leaveMasterData = db.GetEmployeeLeaveMasterDataList().Where(x => x.EmployeeId.Equals(employeeId)).FirstOrDefault();
            var employeeLeaveMasterList = db.GetEmployeeLeaveMasterDataList();
            try
            {
                if (leaveName == "SickLeave")
                {


                    if (leaveMasterData.Sickleave > 0)
                    {
                        result = true;
                    }
                    else
                    {
                        result = false;

                    }



                }
                else if (leaveName == "PrivilageLeave")
                {
                    if (leaveMasterData.Sickleave > 0)
                    {
                        result = true;
                    }
                    else
                    {
                        result = false;

                    }

                }
                else if (leaveName == "CasualLeave")
                {
                    if (leaveMasterData.CasualLeave > 0)
                    {
                        result = true;
                    }
                    else
                    {
                        result = false;

                    }

                }
                else if (leaveName == "LeaveWithoutPay")
                {
                    if (leaveMasterData.LeaveWithoutPay > 0)
                    {
                        result = true;
                    }
                    else
                    {
                        result = false;

                    }
                }

            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }

            return result;

        }



        public bool LeaveWithdraw(string leaveRequestId, bool flag)
        {
            bool result = false;
            try
            {
                var employeeLeaveRequest = db.GetEmployeeLeaveRequestDataByLeaveId(leaveRequestId);
                if (employeeLeaveRequest != null)
                {
                    employeeLeaveRequest.Status = db.GetAppOptionDataList().Where(x => x.ParamValue.Equals(Constants.LEAVE_REQUEST_WITHDRAW)).Select(x => x.ParamId).FirstOrDefault();
                    result = db.UpdateEmployeeLeaveRequest(employeeLeaveRequest);
                    if (flag == true)
                    {
                        if (employeeLeaveRequest.FromDate != null && employeeLeaveRequest.TotalLeave != null)
                        {
                            var attendanceList = db.GetAttendanceDataList();
                            for (int i = 0; i < Convert.ToInt16(employeeLeaveRequest.TotalLeave); i++)
                            {
                                var date = employeeLeaveRequest.FromDate;
                                date = date.AddDays(i);
                                Guid checkExistingLeaves = attendanceList.Where(x => x.Date.Equals(date)).Select(x => x.AttendanceId).FirstOrDefault();
                                if (checkExistingLeaves != Guid.Empty)
                                {
                                    AttendanceData attendance = new AttendanceData();
                                    attendance = (from value in attendanceList
                                                  where value.AttendanceId == checkExistingLeaves
                                                  select value).FirstOrDefault();
                                    if (attendance != null)
                                        db.DeleteAttendance(attendance.AttendanceId.ToString());
                                }

                            }

                            //++
                            employeeLeaveRequest = db.GetEmployeeLeaveRequestDataByLeaveId(leaveRequestId);
                            result = CalculateLeaveOfEmployee(employeeLeaveRequest, true);


                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return result;
        }



    }
}
